# 传统文件操作
file = open("test.txt", "w")
try:
    file.write("Hello, World!")
finally:
    file.close()

# with语法糖 - 自动管理资源
with open("test.txt", "w") as file:
    file.write("Hello, World!")
# 文件会自动关闭，即使发生异常

# 自定义上下文管理器
class MyContext:
    def __enter__(self):
        print("进入上下文")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("退出上下文")
        if exc_type:
            print(f"发生异常: {exc_val}")
        return False  # 不抑制异常

# 使用自定义上下文管理器
with MyContext() as ctx:
    print("在上下文中执行")

# 多个上下文管理器
with open("input.txt") as f1, open("output.txt", "w") as f2:
    f2.write(f1.read())
    